package com.qf.flash.ui.home;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.qf.dblib.dao.entity.LocationBean;
import com.qf.dblib.dao.impl.LocationDao;
import com.qf.flash.R;
import com.qf.flash.http.response.BusinessInfoBean;
import com.qf.flash.model.RegionBean;
import com.qf.flash.mvp.contract.BusinessContract;
import com.qf.flash.mvp.contract.RegionContract;
import com.qf.flash.mvp.presenter.BCPresenter;
import com.qf.flash.mvp.presenter.RegionPresenter;
import com.qf.flash.ui.home.adapter.AreaChosenItem;
import com.qf.flash.ui.home.adapter.ChoseBusinessItem;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.sharedpreferences.SavePermanentSharePrefs;
import com.qf.flashlib.sharedpreferences.SharePrefConstants;
import com.qf.flashlib.util.DensityUtil;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建日期：2020/3/8 on 20:40
 * 描述:
 * 作者:戴旭东
 */
public class ChoseBusinessActivity extends BaseActivity implements BusinessContract.View, RegionContract.View {
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.rv_dialog)
    RecyclerView rvDialog;
    @BindView(R.id.fl_dialog)
    FrameLayout flDialog;

    private RVAdapter<BusinessInfoBean> mAdapter;
    private RVAdapter<RegionBean> areaMsgAdapter;

    protected boolean isRefresh;
    private BCPresenter mBCPresenter;
    private RegionPresenter mRegionPresenter;
    private String orderId;
    private String emchatId;
    private boolean needFeedBack;

    private String cityId;      //	否	String	市id
    private String areaId;      //	否	String	区id
    private String playId;      //	否	String	剧本id
    private String playType;    //	否	String	游戏类型id
    private String longitude;   //	否	String	经度
    private String latitude;    //	否	String	纬度
    private String orderType;   //	否	String	排序类型，1距离排序，不填，综合排序
    private String userId;      //	否	String	当前登录用户id
    private int pageNo = 1;         //	否	Int	页号，默认从1开始
    private String pageSize;    //	否	Int	每页条数，默认30条
    private int currConditionId;
    private List<RegionBean> regionBeans = new ArrayList<>();


    public static void start(Activity activity, String playId, String playTypeID, String orderId, String emchatId) {
        Intent intent = new Intent(activity, ChoseBusinessActivity.class);
        intent.putExtra("playId", playId);
        intent.putExtra("playType", playTypeID);
        intent.putExtra("orderId", orderId);
        intent.putExtra("emchatId", emchatId);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String playId, String playType, String orderId, String emchatId, boolean needFeedBack) {
        Intent intent = new Intent(activity, ChoseBusinessActivity.class);
        intent.putExtra("playId", playId);
        intent.putExtra("playType", playType);
        intent.putExtra("orderId", orderId);
        intent.putExtra("emchatId", emchatId);
        intent.putExtra("needFeedBack", needFeedBack);
        activity.startActivity(intent);
    }

    @Override
    protected void initInject() {
        mBCPresenter = new BCPresenter();
        mRegionPresenter = new RegionPresenter();
        initPresenters(mBCPresenter, mRegionPresenter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chose_business;
    }

    @Override
    protected void initViewAndData() {
        initRefresh();
        initRecyclerView();
        playId = getIntent().getStringExtra("playId");
        playType = getIntent().getStringExtra("playType");
        orderId = getIntent().getStringExtra("orderId");
        emchatId = getIntent().getStringExtra("emchatId");
        needFeedBack = getIntent().getBooleanExtra("needFeedBack", false);
        mRefresh.autoRefresh();
        tvTopTitle.setText("选择商家");

    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new RVAdapter<>(new ChoseBusinessItem(this));
        mAdapter.setOnItemChildClickListener(new RVAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.cb_right:
                        mAdapter.setSingleChosenPosition(position);
                        mAdapter.notifyDataSetChanged();
                        break;
                    case R.id.cl_container:
                        BusinessDetailActivity.start(ChoseBusinessActivity.this, orderId, mAdapter.getData(position).getId(), emchatId, !needFeedBack);
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }


    private void initRefresh() {
        mRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                pageNo++;
                requestData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                pageNo = 1;
                requestData();
            }
        });
    }


    protected void requestData() {
        Map<String, Object> map = new HashMap<>();
        if (currConditionId == R.id.tv_area) {
            map.put("areaId", areaId);
        } else if (currConditionId == R.id.tv_distance) {
            LocationBean locationBean = LocationDao.getInstance().getLocationBean();
            map.put("longitude", locationBean.getLng());
            map.put("latitude", locationBean.getLat());
        }
//        map.put("cityId", cityId);
////        map.put("areaId", areaId);
        map.put("playId", playId);
        map.put("playType", playType);
////        map.put("longitude", longitude);
////        map.put("latitude", latitude);
////        map.put("orderType", orderType);
        map.put("pageNo", pageNo);
        mBCPresenter.getBusinessList(map);
    }

    private void initAreaRv() {
        areaMsgAdapter = new RVAdapter<>(new AreaChosenItem());
        rvDialog.setLayoutManager(new LinearLayoutManager(this));
        rvDialog.setAdapter(areaMsgAdapter);
        areaMsgAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                areaId = areaMsgAdapter.getData(position).getAreaCode();
                areaMsgAdapter.setSingleChosenPosition(position);
                areaMsgAdapter.notifyDataSetChanged();
                mRefresh.autoRefresh();
                dismissDialog();
            }
        });
    }


    @OnClick({R.id.tv_top_back, R.id.tv_zonghe, R.id.tv_distance, R.id.tv_area, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.tv_zonghe:
                currConditionId = R.id.tv_zonghe;
                mRefresh.autoRefresh();
                break;
            case R.id.tv_distance:
                currConditionId = R.id.tv_distance;
                mRefresh.autoRefresh();
                break;
            case R.id.tv_area:
                currConditionId = R.id.tv_area;

                if (regionBeans == null || regionBeans.size() == 0) {
                    String id = SavePermanentSharePrefs.getInstance().getDataString(SharePrefConstants.CITY_ID);
                    mRegionPresenter.getSubCity(id);
                } else if (isShowingDialog) {
                    dismissDialog();
                } else {
                    showAreaDialog();
                }
                break;
            case R.id.tv_sure:
                int singleChosenPosition = mAdapter.getSingleChosenPosition();
                if (singleChosenPosition == -1)
                    return;
                if (needFeedBack) {
                    BusinessInfoBean data = mAdapter.getData(singleChosenPosition);
                    EventBus.getDefault().post(data);
                    finish();
                } else{
                    String id = mAdapter.getData(singleChosenPosition).getId();
                    mBCPresenter.choseBusiness(orderId, id);
                }


                break;
        }
    }

    @Override
    public void setBusinessData(List<BusinessInfoBean> businessInfoData, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        if (isRefresh)
            mAdapter.setDatas(businessInfoData);
        else
            mAdapter.addData(businessInfoData);
        mRefresh.setEnableLoadMore(pageNo < totalPage);

    }

    @Override
    public void choseSuccess() {
        if (needFeedBack) {
            int singleChosenPosition = mAdapter.getSingleChosenPosition();
            BusinessInfoBean data = mAdapter.getData(singleChosenPosition);
            EventBus.getDefault().post(data);
            finish();
        } else {
            FlashLib.showToast("商家选择成功");
        }
        BusinessSuccessActivity.start(this, emchatId);
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
    }

    @Override
    public void setRegionListData(List<RegionBean> regionBeans) {
        if (areaMsgAdapter == null) {
            initAreaRv();
        }
        this.regionBeans = regionBeans;
        areaMsgAdapter.setDatas(this.regionBeans);
        showAreaDialog();
    }

    private ObjectAnimator translationY;
    private boolean isShowingDialog;


    private void showAreaDialog() {
        int y = DensityUtil.dp2px(this, 300);

        if (translationY == null)
            translationY = ObjectAnimator.ofFloat(rvDialog, "translationY", -y, 0);
        translationY.setDuration(200);
        translationY.start();
        isShowingDialog = true;
        flDialog.setBackgroundColor(getResources().getColor(R.color.tra_black_30));
        flDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissDialog();
            }
        });
        rvDialog.setVisibility(View.VISIBLE);
        flDialog.setVisibility(View.VISIBLE);
        translationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animatedFraction = animation.getAnimatedFraction();
                if (animatedFraction == 1 && !isShowingDialog) {
                    flDialog.setBackgroundColor(getResources().getColor(R.color.transparent));
                    rvDialog.setVisibility(View.GONE);
                    flDialog.setVisibility(View.GONE);
                    flDialog.setOnClickListener(null);
                }
            }
        });
    }

    public void dismissDialog() {
        if (isShowingDialog) {
            isShowingDialog = false;
            if (translationY != null)
                translationY.reverse();
        }

    }
}
